#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time
import requests
import re
import json
import sys, os
# from requests_toolbelt import MultipartEncoder

FILE_PATH=os.path.split(os.path.realpath(__file__))[0]

class WeCom(object):
    """docstring for WeCom"""
    def __init__(self):
        self.__clearData()
        self.__loadConfig()

    def __clearAccessToken(self):
        self.__AccessToken = ""
        self.__AccessTokenExpired = 0

    def __clearData(self):
        self.__corpid = ""
        self.__corpsecret = ""
        self.__AgentId = ""
        self.__dataRecord = 0
        self.__clearAccessToken()

    def __loadConfig(self):
        try:
            with open(FILE_PATH + os.sep + "wecom.conf", "r+") as f:
                config = json.loads(f.read())
                # print(config)
                self.__corpid = config['corpid']
                self.__corpsecret = config['corpsecret']
                self.__AgentId = config['AgentId']
                self.__dataRecord = config['dataRecord']
                self.__loadAccessToken()
        except Exception as e:
            print("Load WeCom config failed: " + str(e))
            self.__clearData()
            print("Creating sample config file")
            with open(FILE_PATH + os.sep + "wecom.conf", "w+") as f:
                # help_info = "# Find corpid at https://work.weixin.qq.com/wework_admin/frame#profile\r\n"
                # f.write(help_info)
                config = {
                    'corpid' : 'wwabcddzxdkrsdv',
                    'corpsecret' : 'vQT_03RDVA3uE6JDASDASDAiXUvccqV8mDgLdLI',
                    'AgentId' : 1000002,
                    'dataRecord' : 0
                }
                f.write(json.dumps(config, indent=2))
            print("Creating accessToken.data")
            with open(FILE_PATH + os.sep + "accessToken.data", "w") as f:
                f.write("")

    def getTimestamp(self):
        return (int)(time.time())

    def getAccessToken(self):
        if self.__loadAccessToken():
            return True

        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwabcddzxdkrsdv&corpsecret=vQT_03RDVA3uE6JDASDASDAiXUvccqV8mDgLdLI"
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        params = {
            'corpid': f'{self.__corpid}',
            'corpsecret': f'{self.__corpsecret}'
        }

        try:
            # curl -G -d 'corpid=self.__corpid' -d 'corpsecret=self.__corpsecret' https://qyapi.weixin.qq.com/cgi-bin/gettoken
            timestampNow = self.getTimestamp()
            r = requests.get(url, params=params)
            r.encoding = 'utf-8'
            # print(r.text)
            try:
                accessToken_json = json.loads(r.text)
                error_code = (int)(accessToken_json['errcode'])
                if error_code != 0: # or error_code != '0':
                    error_msg = accessToken_json['errmsg']
                    print("Get accessToken failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                    self.__clearAccessToken()
                    return False
                self.__AccessToken = accessToken_json['access_token']
                expires_in = (int)(accessToken_json['expires_in'])
                self.__AccessTokenExpired = timestampNow + expires_in
                print("accessToken: " + str(self.__AccessToken) + "\r\n" + "AccessTokenExpired: " + str(self.__AccessTokenExpired))
                self.__storeAccessToken()
                return True
            except Exception as e:
                print("Analyze accessToken json failed: " + str(e))
                self.__clearAccessToken()
                return False
        except Exception as e:
            print("Post to get accessToken failed: " + str(e))
            self.__clearAccessToken()
            return False

    def __checkAccessToken(self):
        if self.__AccessToken == "" or self.__AccessTokenExpired == 0 or self.__AccessTokenExpired < self.getTimestamp() + 5:
            return False
        return True

    def __storeAccessToken(self):
        if self.__dataRecord == 0:
            return False
        if not self.__checkAccessToken():
            return False
        with open("accessToken.data", "w+") as f:
            accessToken = {
                'AccessToken': self.__AccessToken,
                'AccessTokenExpired': self.__AccessTokenExpired
            }
            f.write(json.dumps(accessToken, indent=2))
            return True

    def __loadAccessToken(self):
        if self.__dataRecord == 0:
            return False
        try:
            with open("accessToken.data", "r+") as f:
                accessToken = json.loads(f.read())
                self.__AccessToken = accessToken['AccessToken']
                self.__AccessTokenExpired = accessToken['AccessTokenExpired']
                if not self.__checkAccessToken():
                    self.__clearAccessToken()
                    return False
                return True
        except Exception as e:
            print("Load accessToken failed: " + str(e))
            return False


    def senMsg(self, msg):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN"
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}'
        }
        # AgentId = 1000002
        msg_data = {
            'touser' : '@all',
            'msgtype': 'text',
            'agentid' : f'{self.__AgentId}',
            'text' : {
                'content' : f'{msg}'
            },
            'safe' :0
        }
        try:
            r = requests.post(url, params=params, data=json.dumps(msg_data))
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Send WeCom msg failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return False
            return True
        except Exception as e:
            print("Send WeCom msg failed: " + str(e))
            return False

    def senMsg_to_User(self, msg, userID):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN"
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}'
        }
        # AgentId = 1000002
        msg_data = {
            'touser' : f'{userID}',
            'msgtype': 'text',
            'agentid' : f'{self.__AgentId}',
            'text' : {
                'content' : f'{msg}'
            },
            'safe' :0
        }
        try:
            r = requests.post(url, params=params, data=json.dumps(msg_data))
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Send WeCom msg failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return False
            return True
        except Exception as e:
            print("Send WeCom msg failed: " + str(e))
            return False

    def sendMarkdown(self, markdown):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN"
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}'
        }
        # AgentId = 1000002
        msg_data = {
            'touser' : '@all',
            'msgtype': 'markdown',
            'agentid' : f'{self.__AgentId}',
            'markdown' : {
                'content' : f'{markdown}'
            },
            'safe' :0
        }
        try:
            r = requests.post(url, params=params, data=json.dumps(msg_data))
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Send WeCom markdown failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return False
            return True
        except Exception as e:
            print("Send WeCom markdown failed: " + str(e))
            return False

    def getUserID_FromMoble(self, phone_num):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=ACCESS_TOKEN"
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}'
        }
        # AgentId = 1000002
        msg_data = {
            'mobile': f'{phone_num}'
        }
        try:
            r = requests.post(url, params=params, data=json.dumps(msg_data))
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Get userID failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return ''
            UserID = (str)(reslt_json['userid'])
            return UserID
        except Exception as e:
            print("Get userID failed: " + str(e))
            return ''


    def upload_temp_image(self, image_path):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
        url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}',
            'type': 'image'
        }
        # # AgentId = 1000002
        # # msg_data = {
        # #     'touser' : '@all',
        # #     'msgtype': 'markdown',
        # #     'agentid' : f'{self.__AgentId}',
        # #     'markdown' : {
        # #         'content' : f'{markdown}'
        # #     },
        # #     'safe' :0
        # # }
        # headers = {
        #     'Content-Type': 'multipart/form-data',
        #     'Content-Length': f'{len(image)}',
        #     'Content-Disposition': 

        # }
        # m = MultipartEncoder(
        #     fields={image_path: ('file', open(image_path, 'rb'), 'text/plain')},
        # )
        # print(m)
        # print(m.content_type)

        try:
            # r = requests.post(url, params=params, data=m, headers={'Content-Type': m.content_type})
            data = {image_path: open(image_path, 'rb')}  # post jason
            r = requests.post(url, params=params, files=data)
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Wecom upload temp image failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return None
            return reslt_json['media_id']
        except Exception as e:
            print("Wecom upload temp image failed: " + str(e))
            return None

    def upload_temp_image_data(self, image_data):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"
        url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}',
            'type': 'image'
        }
        # # AgentId = 1000002
        # # msg_data = {
        # #     'touser' : '@all',
        # #     'msgtype': 'markdown',
        # #     'agentid' : f'{self.__AgentId}',
        # #     'markdown' : {
        # #         'content' : f'{markdown}'
        # #     },
        # #     'safe' :0
        # # }
        # headers = {
        #     'Content-Type': 'multipart/form-data',
        #     'Content-Length': f'{len(image)}',
        #     'Content-Disposition': 

        # }
        # m = MultipartEncoder(
        #     fields={image_path: ('file', open(image_path, 'rb'), 'text/plain')},
        # )
        # print(m)
        # print(m.content_type)

        try:
            # r = requests.post(url, params=params, data=m, headers={'Content-Type': m.content_type})
            data = {str(int(time.time())): image_data}  # post jason
            r = requests.post(url, params=params, files=data)
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Wecom upload temp image data failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return None
            return reslt_json['media_id']
        except Exception as e:
            print("Wecom upload temp image data failed: " + str(e))
            return None

    def send_image_by_image_id(self, image_id):
        if not self.__checkAccessToken():
            self.getAccessToken()
        sample_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN"
        url = "https://qyapi.weixin.qq.com/cgi-bin/message/send"
        # url = "http://127.0.0.1:11080/"
        params = {
            'access_token': f'{self.__AccessToken}'
        }
        # AgentId = 1000002
        msg_data = {
            'touser' : '@all',
            'msgtype': 'image',
            'agentid' : f'{self.__AgentId}',
            "image":{
                "media_id": image_id
            },
            'safe' :0
        }

        try:
            r = requests.post(url, params=params, data=json.dumps(msg_data))
            # print(r.text)
            reslt_json = json.loads(r.text)
            print(reslt_json)
            error_code = (int)(reslt_json['errcode'])
            if error_code != 0:
                error_msg = reslt_json['errmsg']
                print("Send WeCom image failed, error code: " + str(error_code) + " (" + str(error_msg) + ")")
                return False
            return True
        except Exception as e:
            print("Send WeCom image failed: " + str(e))
            return False

    def send_image(self, image_path):
        image_id = self.upload_temp_image(image_path)
        if not image_id:
            print("Upload temp image failed")
            return False
        return self.send_image_by_image_id(image_id)

    def send_image_by_image_data(self, image_data):
        image_id = self.upload_temp_image_data(image_data)
        if not image_id:
            print("Upload temp image failed")
            return False
        return self.send_image_by_image_id(image_id)

if __name__ == '__main__':
    we = WeCom()
    if len(sys.argv) == 2:
        print(we.senMsg(sys.argv[1]))
    else:
        # # # md = "您的会议室已经预定，稍后会同步到`邮箱` \
        # # #                         >**事项详情** \
        # # #                         >事　项：<font color=\"info\">开会</font> \
        # # #                         >组织者：@miglioguan \
        # # #                         >参与者：@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang \
        # # #                         > \
        # # #                         >会议室：<font color=\"info\">广州TIT 1楼 301</font> \
        # # #                         >日　期：<font color=\"warning\">2018年5月18日</font> \
        # # #                         >时　间：<font color=\"comment\">上午9:00-11:00</font> \
        # # #                         > \
        # # #                         >请准时参加会议。 \
        # # #                         > \
        # # #                         >如需修改会议信息，请点击：[修改会议信息](https://work.weixin.qq.com)"
        # # # print(we.sendMarkdown(md))
        # # # print(we.senMsg("This is a test msg"))
        # # # text_msg = "你的快递已到，请携带工卡前往邮件中心领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中心视频实况</a>，聪明避开排队。"
        # text_msg = "| <a href=\"https://www.baidu.com/\">百度一下，你就知道</a>\n\n<a href=\"https://cn.bing.com/\">必应 必搜</a>"
        # print(we.senMsg(text_msg))
        # userID = we.getUserID_FromMoble(13430388888)
        # print(userID)
        # print(we.senMsg_to_User(text_msg, userID))
        we.send_image('1.jpg')
